package com.ydsungan.web;

import com.alibaba.fastjson.JSON;
import com.ydsungan.bean.Clockin;
import com.ydsungan.bean.Signin;
import com.ydsungan.bean.Student;
import com.ydsungan.bean.Teacher;
import com.ydsungan.service.ClockinService;
import com.ydsungan.service.SigninService;
import com.ydsungan.service.StudentService;
import com.ydsungan.service.TeacherService;
import com.ydsungan.serviceimpl.ClockinServiceImpl;
import com.ydsungan.serviceimpl.SigninServiceImpl;
import com.ydsungan.serviceimpl.StudentServiceImpl;
import com.ydsungan.serviceimpl.TeacherServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class LoginServlet extends HttpServlet {

    private StudentService studentService = null;
    private TeacherService teacherService = null;
    private SigninService signinService = null;
    private ClockinService clockinService = null;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void init() throws ServletException {
        try {
            studentService = new StudentServiceImpl();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            teacherService = new TeacherServiceImpl();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            signinService = new SigninServiceImpl();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            clockinService = new ClockinServiceImpl();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        String id = request.getParameter("id");
        String password = request.getParameter("password");
        logger.info(id + " : " + password);

        Map map = new HashMap();
        map.put("id",id);
        PrintWriter writer = response.getWriter();
        Teacher teacher = teacherService.findTeacherByMap(map);
        Student student = studentService.findStudentByMap(map);

        if(student != null){
            //登录者为student
            if(student.getPassword().equals(password)){
                this.getServletContext().setAttribute("student_has_logined","1");
                this.getServletContext().setAttribute("loginstudent", student);


                //检查老师今天有没有发
                String teacherId = student.getTeacher();

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                Signin signin = null;
                Map map3 = new HashMap();
                map3.put("signinDay", sdf.format(new Date()));
                map3.put("organiser", teacherId);
                logger.info(sdf.format(new Date()));
                List<Signin> list = signinService.getSigninByMap(map3);


                if(list.size() != 0){
                    signin = list.get(0);

                    logger.info("签到日:" + signin.getSigninDay());

                    this.getServletContext().setAttribute("student_check_signin_has_released","1");

                    signin.setSigninTime(signin.getSigninTime().replace("-","至"));
                    Date myDate = null;
                    String str = "";
                    try {
                        myDate = sdf.parse(signin.getSigninDay());
                        SimpleDateFormat formatter = new SimpleDateFormat("E");
                        str = formatter.format(myDate);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    signin.setSigninDay(signin.getSigninDay()+"("+str+")");
                    signin.setReleaseTime(signin.getReleaseTime().split(" ")[1]);
                    this.getServletContext().setAttribute("today_signin_content",signin);
                }else{
                    logger.info("老师还没有发布今天的");
                }

                //学生查询自己是否clockin了
                Map map4 = new HashMap();
                map4.put("day", sdf.format(new Date()));
                map4.put("student", student.getId());
                List<Clockin> clockinList = clockinService.findClockinByMap(map4);
                if(clockinList.size() > 0){
                    this.getServletContext().setAttribute("student_has_clockin","1");

                    Clockin clockin = clockinList.get(0);
                    clockin.setDate(clockin.getDate().split(" ")[1]);
                    this.getServletContext().setAttribute("clockin_content", clockin);
                }



                writer.write(JSON.toJSONString(student));
                logger.info("学生登录成功");
            }else{
                logger.info("学生登录密码错误");
                writer.write("{\"code\":\"0\",\"msg\":\"failure\"}");
            }
        }else if(teacher != null){
            //登录者是teacher
            if(teacher.getPassword().equals(password)){
                logger.info("教师登录密码正确");
                //查询与该老师的发布签到的相关信息。
                String yesterday = "";
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    Date date = new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24);

                    yesterday = sdf.format(date);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                logger.info(yesterday);

                Signin signin = null;
                Map map2 = new HashMap();
                map2.put("signinDay", yesterday);
                map2.put("organiser", teacher.getId());
                List<Signin> list = signinService.getSigninByMap(map2);
                if(list.size() != 0){
                    signin = list.get(0);
                }
                logger.info("昨天发布的签到id号为:"+signin.getId());
                //查处所有学生
                List<Student> studentsList = studentService.findAllStudent();
                this.getServletContext().setAttribute("studentsNum", studentsList.size());

                System.out.println("学生人数："+studentsList.size());

                Map map3 = new HashMap();
                map3.put("signin", signin.getId());
                List<Clockin> clockinsList = clockinService.findClockinByMap(map3);
                logger.info("昨天签到数:" + clockinsList.size());
                //notClockinStudents昨天未签到的学生的列表
                List<Student> notClockinStudents = new ArrayList<Student>();
                int clockinsListSize = clockinsList.size();
                int studentsListSize = studentsList.size();
                for(int i = 0; i < studentsListSize; i++){
                    Student student1 = studentsList.get(i);
                    int j ;
                    for(j = 0; j < clockinsListSize; j++){
                        if(clockinsList.get(j).getStudent().equals(student1.getId())){
                            //这个学生昨天签到了
                            break;
                        }
                    }
                    if(j == clockinsListSize){
                        //这个学生昨天没有签到
                        notClockinStudents.add(student1);
                    }
                }
                logger.info("昨日未签人数:"+notClockinStudents.size());
                this.getServletContext().setAttribute("notClockinStudents", notClockinStudents);
                this.getServletContext().setAttribute("notClockinStudentsSize", notClockinStudents.size());
                this.getServletContext().setAttribute("teacher_has_logined","1");
                this.getServletContext().setAttribute("loginteacher", teacher);

                //登录时查看今天的签到有没有发布
                String today = "";
                try {
                    Date date = new Date();
                    today = sdf.format(date);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                logger.info("今天是:" + today);

                Map map4 = new HashMap();
                map4.put("signinDay", today);
                map4.put("organiser", teacher.getId());
                List<Signin> list2 = signinService.getSigninByMap(map4);
                if(list2.size() > 0){
                    Signin signin5 = list2.get(0);
                    this.getServletContext().setAttribute("signin_has_released","1");
                    signin5.setSigninTime(signin5.getSigninTime().replace("-","至"));
                    Date myDate = null;
                    String str = "";
                    try {
                        myDate = sdf.parse(signin5.getSigninDay());
                        SimpleDateFormat formatter = new SimpleDateFormat("E");
                        str = formatter.format(myDate);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    signin5.setSigninDay(signin5.getSigninDay()+"("+str+")");
                    signin5.setReleaseTime(signin5.getReleaseTime().split(" ")[1]);
                    this.getServletContext().setAttribute("today_signin_content", signin5);
                }else{
                    logger.info("今天没有发布");
                }


                writer.write(JSON.toJSONString(teacher));
            }else{
                logger.info("教师登录密码错误");
                writer.write("{\"code\":\"0\",\"msg\":\"failure\"}");
            }
        }else{
            logger.info("没有该账号");
            writer.write("{\"code\":\"0\",\"msg\":\"failure\"}");
        }
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

}
